<?php
class ArticlesController extends AppController {
	var $name = 'Articles';
	var $helpers = array('Tinymce');
	var $uses = array('Article', 'Category', 'Keyword', 'User', 'UserCategory', 'Check');
	function beforeFilter(){
		parent::beforeFilter();
		$this->set('topmenuLinkActive', 1);
	}

	function index() {
		$tabActive = 0;
		$this->Article->recursive = 0;
		$this->paginate = array('Article' => array('order' => 'Article.created DESC'));
		if($this->Session->read('Auth.User.role') == ROLE_AUTHOR){
			$articles = $this->paginate('Article', array('Article.user_id' => $this->Session->read('Auth.User.id')));
			$this->set(compact('articles' ,'tabActive'));
		}
		if($this->Session->read('Auth.User.role') == ROLE_EDITOR){
			$categories = $this->UserCategory->find('list', array(
				'recursive'=> -1,
				'conditions'=> array('UserCategory.user_id' => $this->Session->read('Auth.User.id')),
				'fields'=> array('UserCategory.category_id')
			));

			$users = $this->User->find('list', array(
				'recursive'=> -1,
				'conditions'=> array('User.role' => ROLE_AUTHOR),
				'fields'=> array('User.id')
			));
			//cac bai viet user da active hoac bai viet duplicate(tu bai viet user)
			//thuoc category cua manager quan ly
			$articles = $this->paginate('Article', array(
					'OR' => array(
						array('Article.user_id'=> $users,'Article.status'=> ARTICLE_STATUS_POSTED),
						array('Article.user_id'=> $this->Session->read('Auth.User.id'))
					),
					'Article.category_id' => $categories,
			));
			$this->set(compact('articles' ,'tabActive'));
			$this->render('manage_index');
		}
	}

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid article'));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('article', $this->Article->read(null, $id));
	}

	function add() {
		if (!empty($this->request->data)) {
			$this->Article->create();
			$this->request->data['Article']['user_id'] = $this->Session->read('Auth.User.id');
			if(isset($this->request->data['Article']['sub_category_id']) && !empty($this->request->data['Article']['sub_category_id'])){
				$this->request->data['Article']['category_id'] = $this->request->data['Article']['sub_category_id'];
			}

			if ($this->Article->save($this->request->data)) {
				$this->Session->setFlash(__('The article has been saved'), 'alert_success');
				if(isset($this->request->data['Article']['task']) && ($this->request->data['Article']['task'] == 'save2new')){
					$this->redirect(array('action' => 'add'));
				}else{
					$this->redirect(array('action' => 'index'));
				}
			} else {
				$this->Session->setFlash(__('The article could not be saved. Please, try again.'));
			}
		}
		$title_for_layout =  __('Add new article');
		$categories = $this->Category->find('list',array(
			'recursive' => -1,
			'conditions' => array('Category.parent_id'=>null),
			'fields' => array('Category.id', 'Category.title')
		));
		if(isset($_GET['k'])){
			$keywords = $this->Keyword->find('list',array(
				'recursive' => -1,
				'fields' => array('Keyword.id', 'Keyword.title'),
				'conditions' => array('Keyword.id'=>explode(',', $_GET['k']))
			));
		}
		$this->set(compact('title_for_layout', 'topmenuLinkActive' ,'categories', 'keywords'));
	}

	function edit($id = null) {
		if (!$id && empty($this->request->data)) {
			$this->Session->setFlash(__('Invalid article'),'alert_error');
			$this->redirect(array('action' => 'index'));
		}

		$article = $this->Article->find('first',array(
			'recursive' => -1, 
			'conditions' => array('Article.id'=> $id, 'Article.user_id' => $this->Session->read('Auth.User.id'))
		));
		if(empty($article) || !in_array($article['Article']['status'],array(ARTICLE_STATUS_DRAFT, ARTICLE_STATUS_REJECTED))){
			$this->Session->setFlash(__('The article could not be edited. Please, try again.'),'alert_error');
			$this->redirect(array('action' => 'index'));
		}

		if (!empty($this->request->data)) {
			if ($this->Article->save($this->request->data)) {
				$this->Session->setFlash(__('The article has been saved'),'alert_success');
				if(isset($this->request->data['Article']['task']) && ($this->request->data['Article']['task'] == 'save2new')){
					$this->redirect(array('action' => 'add'));
				}else{
					$this->redirect(array('action' => 'index'));
				}
			} else {
				$this->Session->setFlash(__('The article could not be saved. Please, try again.'),'alert_error');
			}
		}
		if (empty($this->request->data)) {
			$this->request->data = $this->Article->read(null, $id);
		}
		$title_for_layout =  __('Edit article');
		$categories = $this->Category->find('list',array(
			'recursive' => -1,
			'conditions' => array('Category.parent_id'=>null),
			'fields' => array('Category.id', 'Category.title')
		));
		$this->set(compact('title_for_layout', 'categories'));
	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for article'));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Article->delete($id)) {
			$this->Session->setFlash(__('Article deleted'), 'alert_success');
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('Article was not deleted'), 'alert_error');
		$this->redirect(array('action' => 'index'));
	}

	function filter($type = null){
		$conditions = array('Article.user_id' => $this->Session->read('Auth.User.id'));
		if($this->Session->read('Auth.User.role') == ROLE_EDITOR){
			$categories = $this->UserCategory->find('list', array(
				'recursive'=> -1,
				'conditions'=> array('UserCategory.user_id' => $this->Session->read('Auth.User.id')),
				'fields'=> array('UserCategory.category_id')
			));

			$users = $this->User->find('list', array(
				'recursive'=> -1,
				'conditions'=> array('User.role' => ROLE_AUTHOR),
				'fields'=> array('User.id')
			));
		}
		switch($type){
			case 'accept':
				$tabActive = 1;
				$conditions['Article.status'] = ARTICLE_STATUS_ACCEPTED;
				break;
			case 'reject':
				$tabActive = 2;
				$conditions['Article.status'] = ARTICLE_STATUS_REJECTED;
				break;
			case 'uncheck':
				if($this->Session->read('Auth.User.role') == ROLE_EDITOR){
					$tabActive = 1;
					//cac bai viet user da post
					//thuoc category cua manager quan ly
					$conditions = array(
						'Article.user_id'=> $users,
						'Article.status'=> ARTICLE_STATUS_POSTED,
						'Article.category_id' => $categories,
					);
				}
				break;
			case 'recent':
				if($this->Session->read('Auth.User.role') == ROLE_EDITOR){
					$tabActive = 2;
					$conditions = array(
						'Article.checker' => $this->Session->read('Auth.User.id'),
						'DATE(Article.check_time)'=> date('Y-m-d')
					);
				}
				break;
			case 'checked':
				if($this->Session->read('Auth.User.role') == ROLE_EDITOR){
					$tabActive = 3;
					//cac bai viet user da check
					//thuoc category cua manager quan ly
					$conditions = array(
						'Article.user_id'=> $users,
						'Article.checker'=> $this->Session->read('Auth.User.id'),
						'Article.category_id' => $categories,
					);
				}
				break;
			default:
				$tabActive = 0;
		}

		$this->Article->recursive = 0;
		$this->set('articles', $this->paginate('Article',$conditions));

		$this->set(compact('tabActive','articles'));
		if($this->Session->read('Auth.User.role') == ROLE_AUTHOR){
			$this->render('index');
		}
		if($this->Session->read('Auth.User.role') == ROLE_EDITOR){
			$this->render('manage_index');
		}
	}

	/*
	 * kiem duyet bai viet cua manager
	 */
	function check($id = null){
		$categories = $this->UserCategory->find('list', array(
			'recursive'=> -1,
			'fields'=> array('UserCategory.category_id'), 
			'conditions'=> array('UserCategory.user_id'=> $this->Session->read('Auth.User.id'))
		));
		if(!empty($this->request->data)){
			$this->Check->create();
			$this->Check->save(array('Check'=> array(
				'article_id'=> $id,
				'user_id'=> $this->Session->read('Auth.User.id'),
				'comment'=> $this->request->data['Article']['comment']
			)));
			
			$this->Article->id = $id;
			$data = array('Article'=> array(
				'checker'=> $this->Session->read('Auth.User.id'),
				'check_time'=> date('Y-m-d H:i:s'),
				'status'=> $this->request->data['Article']['status'],
			));
			if($this->request->data['Article']['status'] == ARTICLE_STATUS_REJECTED){
				$data['Article']['rating'] = null;
			}else{
				$data['Article']['rating'] = $this->request->data['Article']['rating'];
			}
			if($this->Article->save($data)){
				$this->Session->setFlash(__('Check successful'), 'alert_success');
				$this->redirect(array('action'=> 'filter', 'recent'));
			};
		}
		
		if(empty($this->request->data)){
			$this->request->data = $this->Article->find('first', array(
				'contain'=> array('Category', 'Check.User'),
				'conditions'=> array(
					'Article.id'=> $id,
					'Article.status'=> ARTICLE_STATUS_POSTED,
					'Article.category_id'=> $categories,
				)
			));
		}
		$this->set(compact('article'));
	}
	
	//duplicate a article at manager screen
	function duplicate($id = null){
		$article = $this->Article->find('first',array(
			'recursive'=> -1,
			'conditions'=> array('Article.id'=> $id),
			'fields'=> array('category_id', 'title', 'link', 'content', 'keyword', 'tag')
		));
		if(!empty($article)){
			$article['Article']['status'] = ARTICLE_STATUS_POSTED;
			$article['Article']['user_id'] = $this->Session->read('Auth.User.id');
			$this->Article->create();
			if($this->Article->save($article)){
				$this->redirect(array('action'=> 'edit', $id));
			}else{
				$this->Session->setFlash(__('Error save. Please try again.'));
			};
		}else{
			$this->Session->setFlash(__('Invalid article id'));
		}
		$this->redirect($this->referer());
	}


	function admin_index() {
		$title_for_layout = __('Manage Article');
		$this->Article->recursive = 0;
		$this->paginate = array('Article' => array('order' => 'Article.created DESC'));
		$this->set('articles', $this->paginate());
	}

	function admin_view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid article'));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('article', $this->Article->read(null, $id));
	}

	function admin_add() {
		if (!empty($this->request->data)) {
			$this->Article->create();
			if ($this->Article->save($this->request->data)) {
				$this->Session->setFlash(__('The article has been saved'));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The article could not be saved. Please, try again.'));
			}
		}
		$users = $this->Article->User->find('list');
		$this->set(compact('users'));
	}

	function admin_edit($id = null) {
		if (!$id && empty($this->request->data)) {
			$this->Session->setFlash(__('Invalid article'));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->request->data)) {
			if ($this->Article->save($this->request->data)) {
				$this->Session->setFlash(__('The article has been saved'));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The article could not be saved. Please, try again.'));
			}
		}
		if (empty($this->request->data)) {
			$this->request->data = $this->Article->read(null, $id);
		}
		$users = $this->Article->User->find('list');
		$this->set(compact('users'));
	}

	function admin_delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for article'));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Article->delete($id)) {
			$this->Session->setFlash(__('Article deleted'));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('Article was not deleted'));
		$this->redirect(array('action' => 'index'));
	}
}
